<script lang="ts">
export default {
  name: "OperateManualTaskEditDialog"
}
</script>

<!--
 * @Descripttion: 编辑对话框
 * @version:
 * @Author: hupengwu
 * @Date: 2022-10-24 09:10:28
 * @LastEditors: hupengwu
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" width="1000px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="100px">

      <!-- 编辑框：任务名称 -->
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="dataState.formData.taskName" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <!-- 下拉框：设备类型 -->
      <el-form-item label="设备厂商" prop="manufacturer">
        <el-select v-model="dataState.formData.manufacturer" placeholder="请选择"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="设备类型" prop="deviceType">
          <el-select v-model="dataState.formData.deviceType" placeholder="请选择"
                     @change="handleSelectDeviceType">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-select v-model="dataState.formData.deviceName" placeholder="请选择">
            <el-option
              v-for="item in dataState.deviceNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>


      <!-- 下拉框：设备类型 -->
      <el-form-item label="操作名称" prop="operateName">
        <el-select v-model="dataState.formData.operateName" placeholder="请选择">
          <el-option
            v-for="item in dataState.operateNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="操作模式" prop="operateMode">
          <el-select v-model="dataState.formData.operateMode" placeholder="请选择">
            <el-option
              v-for="item in dataState.operateModeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <el-form-item label="通信超时" prop="timeout">
        <el-input v-model.number="dataState.formData.timeout"/>
      </el-form-item>


      <!-- 下拉框：配置参数 -->
      <el-form-item label="模板参数" prop="paramJson">
        <el-input v-model="dataState.formData.paramJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>
    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {
  OperateManualTaskItem,
  OperateRequestItem
} from "@/api/device/operate/task/manual/types";
import {listOption2List, listOptionList} from "@/api/option";
import {listOptions} from "@/api/device/device";
import {DeviceOperateQueryParam} from "@/api/repo/comp/local/types";
import {DeviceQueryParam} from "@/api/device/device/types";
import {listOperateOptionList} from "@/api/repo/comp/local";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加模板',
  // 表单数据
  formData: {
    id: 0,
    deviceName: '',
    deviceType: '',
    manufacturer: '',
    taskName: '',
    taskParam: {},
    operateName: '',
    operateMode: '',
    param: '',
    paramJson: '',
    timeout: 2000,
  },

  // 厂商类型选项
  manufacturerOptions: [] as OptionType[],
  // 设备类型选项
  deviceTypeOptions: [] as OptionType[],
  // 设备名称选项
  deviceNameOptions: [] as OptionType[],
  // 操作名称选项
  operateNameOptions: [] as OptionType[],
  // 操作模式选项
  operateModeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    taskName: [{required: true, message: '不能为空', trigger: 'blur'}],
    manufacturer: [{required: true, message: '不能为空', trigger: 'blur'}],
    deviceName: [{required: true, message: '不能为空', trigger: 'blur'}],
    deviceType: [{required: true, message: '不能为空', trigger: 'blur'}],
    operateName: [{required: true, message: '不能为空', trigger: 'blur'}],
    operateMode: [{required: true, message: '不能为空', trigger: 'blur'}],
  },
});

/**
 * 设备类型下拉框
 * @taskParam value
 */
function handleSelectManufacturer(value: any) {
  listDeviceTypeOption(true);
}

/**
 * 设备类型下拉框
 * @taskParam value
 */
async function handleSelectDeviceType(value: any) {
  // 查询设备类型下的设备
  listDeviceNameOption(true);

  // 查询设备类型下的设备
  listOperateNameOption(true);
}

function listDeviceTypeOption(nextMode: boolean) {
  if (nextMode) {
    dataState.deviceTypeOptions = [];
    dataState.formData.deviceType = '';
  }

  // 查询设备类型下的设备
  let manufacturer = dataState.formData.manufacturer;

  // 查询厂商的设备类型
  listOption2List("OperateEntity", "manufacturer", manufacturer, 'deviceType').then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (nextMode && dataState.deviceTypeOptions.length > 0){
        dataState.formData.deviceType = dataState.deviceTypeOptions[0].value;
        listDeviceNameOption(nextMode);
        listOperateNameOption(nextMode);
    }
  });
}

function listDeviceNameOption(nextMode: boolean) {
  if (nextMode) {
    dataState.deviceNameOptions = [];
    dataState.formData.deviceName = '';
  }

  // 查询设备类型下的设备
  let dataForm = {} as DeviceQueryParam;
  dataForm.manufacturer = dataState.formData.manufacturer;
  dataForm.deviceType = dataState.formData.deviceType;
  listOptions("deviceName",dataForm).then(({data}) => {
    dataState.deviceNameOptions = data;
    if (nextMode && dataState.deviceNameOptions.length>0){
      dataState.formData.deviceName = dataState.deviceNameOptions[0].value;
    }
  });
}

function listOperateNameOption(nextMode: boolean) {
  if (nextMode) {
    dataState.operateNameOptions = [];
    dataState.formData.operateName = '';
  }

  let operateForm = {} as DeviceOperateQueryParam;
  operateForm.manufacturer = dataState.formData.manufacturer;
  operateForm.deviceType = dataState.formData.deviceType;
  listOperateOptionList(operateForm).then(({data}) => {
    dataState.operateNameOptions = data;

    if (nextMode && dataState.operateNameOptions.length > 0) {
        dataState.formData.operateName = dataState.operateNameOptions[0].value;
        listOperateModeOption(true);
    }
  });
}

function listOperateModeOption(nextMode: boolean) {
  if (nextMode) {
    dataState.operateModeOptions = [];
    dataState.formData.operateMode = '';
  }

  let operateForm = {} as DeviceOperateQueryParam;
  operateForm.manufacturer = dataState.formData.manufacturer;
  operateForm.deviceType = dataState.formData.deviceType;
  operateForm.operateName = dataState.formData.operateName;
  listOperateOptionList(operateForm).then(({data}) => {
    dataState.operateModeOptions = data;

    if (nextMode && dataState.operateModeOptions.length > 0) {
      dataState.formData.operateMode = dataState.operateModeOptions[0].value;
    }
  });
}

/**
 * 取消
 */
function handleCancel() {
  //执行调用<operateTemplate-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

function verifyTaskParam(): boolean {
  if (dataState.formData.taskName === undefined || dataState.formData.taskName === '') {
    ElMessage.info('任务名称，不能为空!');
    return false;
  }

  dataState.formData.paramJson = dataState.formData.paramJson.trim();
  if (!dataState.formData.paramJson.startsWith('{')) {
    ElMessage.info('输入参数，不是一个JSON对象，格式应该为{}');
    return false;
  }

  try {
    let requestItem = {} as OperateRequestItem;
    requestItem.operateMode = dataState.formData.operateMode;
    requestItem.operateName = dataState.formData.operateName;
    requestItem.deviceName = dataState.formData.deviceName;
    requestItem.deviceType = dataState.formData.deviceType;
    requestItem.manufacturer = dataState.formData.manufacturer;
    requestItem.timeout = dataState.formData.timeout;
    requestItem.param = JSON.parse(dataState.formData.paramJson as string);

    let requestVOS = [] as OperateRequestItem[];
    requestVOS.push(requestItem);
    dataState.formData.taskParam = requestVOS;

    return true;
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return false;
  }
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (!verifyTaskParam()) {
    return;
  }

  if (dataState.type === 'create') {
    // 执行调用<operateTemplate-edit-dialog @create="createEdit">的create
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    //执行调用<operateTemplate-edit-dialog @update="updateEdit">
    emit('update', dataState.formData);
  }
}

/**
 * 初始化对话框
 * @taskParam type 对话框类型
 * @taskParam entity 实体
 */
function initEditData(type: string, entity: OperateManualTaskItem) {
  if (entity !== undefined) {
    dataState.formData.taskName = entity.taskName;
    dataState.formData.deviceName = entity.deviceName;
    dataState.formData.deviceType = entity.deviceType;
    dataState.formData.manufacturer = entity.manufacturer;
    dataState.formData.taskParam = entity.taskParam;
    dataState.formData.operateName = entity.operateName;

    listDeviceTypeOption(false);
    listDeviceNameOption(false);
    listOperateNameOption(false);
    listOperateModeOption(false);

    // 取出数组的第一个元素
    const requestItems = entity.taskParam as OperateRequestItem[];
    if (requestItems.length > 0) {
      dataState.formData.operateMode = requestItems[0].operateMode;
      dataState.formData.operateName = requestItems[0].operateName;
      dataState.formData.deviceName = entity.deviceName;
      dataState.formData.timeout = requestItems[0].timeout;
      dataState.formData.paramJson = JSON.stringify(requestItems[0].param, null, 5);
    }
  } else {
    dataState.formData.taskName = '';
    dataState.formData.deviceName = '';
    dataState.formData.deviceType = '';
    dataState.formData.manufacturer = '';
    dataState.formData.taskParam = {};
    dataState.formData.operateMode = '';
    dataState.formData.operateName = '';
    dataState.formData.timeout = 2000;
    dataState.formData.param = '{}';
  }

  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增配置';

    dataState.formData.id = 0;

    if (dataState.formData.paramJson === ''){
      dataState.formData.paramJson = '{}';
    }

    return;
  }

  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改配置';

    dataState.formData.id = entity.id as number;
    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 设备厂商/设备类型，两级初始化
  listOptionList("OperateEntity", "manufacturer").then(async ({data}) => {
    dataState.manufacturerOptions = data;
  });
});

</script>
